<template>
    <a-modal v-model:open="dialogVisible" width="650px" :footer="null">
        <a-form :model="form" :rules="rules" ref="formRef" :label-col="{ span: 10 }" :wrapper-col="{ span: 20 }">
            <a-row style="margin-bottom: 20px;">
                <a-col>
                    <span style="font-weight: bold;">
                        您现在正在{{ isEdit ? '' : '为' }}
                    </span>
                    <span style="color: #1890ff;">「{{ form.deptName }}」</span>
                    <span style="font-weight: bold;">
                        {{ isEdit ? '中修改用户信息' : '添加新用户' }}
                    </span>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="8">
                    <a-form-item label="用户名" name="userName">
                        <a-input v-model:value="form.userName" placeholder="请输入用户名" />
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="密码" name="psw">
                        <a-input-password
                            v-model:value="form.psw"
                            placeholder="请输入密码"
                            :iconRender="visible => visible ? h(EyeInvisibleOutlined) : h(EyeOutlined)"
                        />
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="8">
                    <a-form-item label="姓名" name="realName">
                        <a-input v-model:value="form.realName" placeholder="请输入姓名" />
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="职称" name="title">
                        <a-select v-model:value="form.title" placeholder="请选择职称">
                            <a-select-option value="教师">教师</a-select-option>
                            <a-select-option value="讲师">讲师</a-select-option>
                            <a-select-option value="教授">教授</a-select-option>
                            <a-select-option value="学生">学生</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :span="8"></a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="8">
                    <a-form-item label="教育经历" name="eudHistory">
                        <a-select v-model:value="form.eudHistory" placeholder="请选择教育经历">
                            <a-select-option value="本科生">本科生</a-select-option>
                            <a-select-option value="研究生">研究生</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="学历" name="diploma">
                        <a-select v-model:value="form.diploma" placeholder="请选择学历">
                            <a-select-option value="本科">本科</a-select-option>
                            <a-select-option value="硕士">硕士</a-select-option>
                            <a-select-option value="博士">博士</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="出生日期">
                        <a-date-picker
                            v-model:value="form.birth"
                            show-time
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            style="width: 100%;"
                        />
                    </a-form-item>
                </a-col>
                <a-col :span="8"></a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="8">
                    <a-form-item label="头像">
                        <a-upload
                            class="avatar-uploader"
                            :customRequest="uploadAvatar"
                            :beforeUpload="beforeUpload"
                            :showUploadList="false"
                        >
                            <template v-if="form.faceImg">
                                <div class="avatar-preview">
                                    <img :src="form.faceImg" class="avatar" />
                                    <div class="avatar-remove" @click.stop="removeAvatar">
                                        <CloseOutlined />
                                    </div>
                                </div>
                            </template>
                            <template v-else>
                                <div class="avatar-uploader-icon">
                                    <PlusOutlined />
                                </div>
                            </template>
                        </a-upload>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-form-item :wrapper-col="{ span: 24 }" style="text-align: right;">
                <a-button @click="dialogVisible = false" style="margin-right: 10px;">取消</a-button>
                <a-button type="primary" @click="submitForm">确定</a-button>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup>
import webConfig from '@/GlobalParas';
import { ref, reactive, h } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';
import { EyeOutlined, EyeInvisibleOutlined, CloseOutlined, PlusOutlined } from '@ant-design/icons-vue';


const showPassword = ref(false);
const dialogVisible = ref(false);
const formRef = ref(null);
const isEdit = ref(false); // 是否编辑状态

const rules = {
    deptId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
    userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    title: [{ required: true, message: '请选择职称', trigger: 'change' }],
    eudHistory: [{ required: true, message: '请选择教育经历', trigger: 'change' }],
    diploma: [{ required: true, message: '请选择学历', trigger: 'change' }],
};

const form = reactive({
    tableKey:'',
    deptId: '',
    userName: '',
    psw: '',
    realName: '',
    title: '',
    eudHistory: '',
    diploma: '',
    birth: '',
    faceImg: '',
    flagDel: 0,
    sort: 0
});

const emit = defineEmits(['success']);

// function togglePasswordVisible() {
//     showPassword.value = !showPassword.value;
// }

const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    const isLt2M = file.size / 1024 / 1024 < 50;

    if (!isImage) {
        message.error('上传头像只能是图片文件!');
    }
    if (!isLt2M) {
        message.error('上传头像图片大小不能超过 50MB!');
    }
    return isImage && isLt2M;
}

const uploadAvatar = (options) => {
    const formData = new FormData();
    formData.append('file', options.file);

    let url = webConfig.postUrl + '/upload';

    axios.post(url, formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }).then(res => {
        form.faceImg = webConfig.downLoadPath + res.data;
        message.success('头像上传成功');
    }).catch(error => {
        message.error('头像上传失败');
    });
}

function removeAvatar() {
    form.faceImg = '';
}

function openDialog(deptNode, editMode = false) {
    dialogVisible.value = true;
    isEdit.value = editMode;

    if (editMode) {
        Object.assign(form, deptNode);
        form.deptName = deptNode.deptName || '';
    } else {
        Object.assign(form, {
        tableKey: '',
        deptId: deptNode.key,
        deptName: deptNode.title,
        userName: '',
        psw: '',
        realName: '',
        title: '',
        eudHistory: '',
        diploma: '',
        birth: '',
        faceImg: '',
        flagDel: 0,
        sort: 0
    });
    }
}

defineExpose({ openDialog })

const submitForm = () => {
    formRef.value.validate().then(() => {
        const url = isEdit.value ?
            webConfig.postUrl + '/systemUser/editUser' :
            webConfig.postUrl + '/systemUser/addUser';
    
        axios.post(url, JSON.stringify(form), {
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(res => {
            if (res.data === "success") {
                message.success(isEdit.value ? '修改用户信息成功' : '添加用户信息成功');
                dialogVisible.value = false;
                emit('success');
            } else if (res.data === "existed") {
                message.warning('用户名已存在，请更换用户名');
            } else {
                message.error(isEdit.value ? '修改用户信息失败' : '添加用户信息失败');
            }
        }).catch(error => {
            if (error !== 'cancel' && error !== 'close') {
                message.error(isEdit.value ? '修改用户信息失败' : '添加用户信息失败');
            }
        })

    })
    // try {
    //     await formRef.value.validate();

    //     const url = isEdit.value ?
    //         webConfig.postUrl + '/systemUser/editUser' :
    //         webConfig.postUrl + '/systemUser/addUser';

    //     const res = await axios.post(url, JSON.stringify(form), {
    //         headers: {
    //             'Content-Type': 'application/json'
    //         }
    //     });

    //     if (res.data === "success") {
    //         message.success(isEdit.value ? '修改用户信息成功' : '添加用户信息成功');
    //         dialogVisible.value = false;
    //         emit('success');
    //     } else if (res.data === "existed") {
    //         message.warning('用户名已存在，请更换用户名');
    //     } else {
    //         message.error(isEdit.value ? '修改用户信息失败' : '添加用户信息失败');
    //     }
    // } catch (error) {
    //     if (error !== 'cancel' && error !== 'close') {
    //         message.error(isEdit.value ? '修改用户信息失败' : '添加用户信息失败');
    //     }
    // }
}
</script>

<style scoped>
.avatar-uploader {
  border-radius: 6px;
}

.avatar-uploader :deep(.ant-upload.ant-upload-select) {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader-icon {
  font-size: 24px;
  color: #8c939d;
}

.avatar-uploader .avatar-preview {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 6px;
  overflow: hidden;
  background-color: #f5f5f5;
  border: 1px solid #d9d9d9;
}

.avatar-uploader .avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.avatar-uploader .avatar-remove {
  position: absolute;
  top: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 24px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>